package com.kvest.NewLocationTest;

import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LoggerService {
    private static final String TAG = "KVEST_TAG";
    private static LoggerService instance;
    private static final Object lock = new Object();

    private DataOutputStream dos;
    private SimpleDateFormat sdf;

    public static LoggerService getInstance() {
        synchronized (lock) {
            if (instance == null) {
                instance = new LoggerService();
            }
        }

        return instance;
    }

    private LoggerService() {
        sdf = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ");
        String fileName = getLogFileName();
        if (fileName.equals("")) {
            return;
        }

        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            dos = new DataOutputStream(new FileOutputStream(file, true));
        } catch (IOException ioException) {
            dos = null;
        }
    }

    public void writeLog(String value) {
        Log.d(TAG, value);
        if (dos != null) {
            try {
                dos.writeUTF(sdf.format(new Date()) + value + "\n");
            } catch (IOException ioException) {}
        }
    }

    private String getLogFileName() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Kvest_logs" + File.separator + "log.txt";
        } else {
            return "";
        }
    }
}
